chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message as the expected format...
    if(msg.action == 'api'){
        // console.log("数据返回", msg.data);
        msg.data.action = 'proxy_api_response';
        // document.getElementById("mabang-proxy-api-extension-input").value = msg.data;        
        chrome.runtime.sendMessage({ action: 'proxyApi', url: 'http://172.16.99.131:9998/print/', params : msg.data }, (response) => {
            console.log(response, ' ======')
            window.postMessage({action:"proxy_api", response}, "*");
        })
        // sendResponse("api sended")
    }
    if(msg.action == 'init'){
        injectInitDom()
        sendResponse("initialized")
    }
    if(msg.action == 'refresh'){
        console.log(msg, 'tab refreshed')
        injectInitDom()
        sendResponse("initialized")
    }
    sendResponse()
});

injectInitDom();

function injectInitDom(){
    console.log("chrome extension initialized")
    if(document.getElementById("mabang-proxy-api-extension-input")){
        return
    }
    var messageInput = document.createElement("input");
    messageInput.type = "text";
    messageInput.id = "mabang-proxy-api-extension-input";
    messageInput.style.display = 'none';
    document.body.appendChild(messageInput);
}

window.parent.addEventListener("message", function( event ) {
    event = event.data;
    if(event && event.action && event.action == 'proxy_api'){
        window.postMessage({action:"chrome_extension_exists", data : {}}, "*");
        chrome.runtime.sendMessage({ action: 'proxyApi', url: 'http://localhost:9998/print/', params : event.params }, (data) => {
            window.postMessage({action:"proxy_api_response", response: data.response}, "*");
        })
        // console.log("开始调用", {action : 'send-api', params: event.params})
        // chrome.runtime.sendMessage({action : 'send-api', params: event.params}, function(response) {
        //     if (!chrome.runtime.lastError) {
                
        //     }else{
        //         console.log("请保持插件面板打开")
        //     }
        // });
    }
})